package com.github.common.extend.demo.config.filetask;

import lombok.extern.slf4j.Slf4j;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.List;
import java.util.function.Supplier;

/**
 * 文件任务拦截器
 * @author wangjj7
 * @date 2023/8/11
 * @description
 */
public interface FileTaskManagerInterceptor {

    /**
     * 任务执行前
     * @param fileTaskParam
     */
    void preExe(FileTaskParam fileTaskParam);

    /**
     * 文件创建成功后执行
     */
    void postFileBuild(Supplier<InputStream> fileSupplier , FileTask fileTask);

    /**
     * 任务执行后
     * @param fileTask
     * @param e 任务执行中抛的异常，如果没有报错则传null
     */
    void postExe(FileTask fileTask, Exception e);

    /**
     * 拦截链
     */
    @Slf4j
    class InterceptorChain implements FileTaskManagerInterceptor {

        private final List<FileTaskManagerInterceptor> interceptors = new ArrayList<>();

        public InterceptorChain(List<FileTaskManagerInterceptor> interceptors) {
            if (interceptors != null && interceptors.size() > 0) {
                this.interceptors.addAll(interceptors);
            }
        }

        public InterceptorChain() {
        }

        @Override
        public void preExe(FileTaskParam fileTaskParam) {
            for (FileTaskManagerInterceptor interceptor : interceptors) {
                try {
                    log.error("{}执行" ,interceptor);
                    interceptor.preExe(fileTaskParam);
                }catch (Exception e){
                    log.error("{}执行异常" ,interceptor ,e);
                }
            }
        }

        @Override
        public void postFileBuild(Supplier<InputStream> fileSupplier , FileTask fileTask) {
            for (FileTaskManagerInterceptor interceptor : interceptors) {
                try {
                    log.error("{}执行" ,interceptor);
                    interceptor.postFileBuild(fileSupplier , fileTask);
                }catch (Exception e){
                    log.error("{}执行异常" ,interceptor ,e);
                }
            }
        }

        @Override
        public void postExe(FileTask fileTask, Exception e) {
            for (FileTaskManagerInterceptor interceptor : interceptors) {
                try {
                    log.error("{}执行" ,interceptor);
                    interceptor.postExe(fileTask,e);
                }catch (Exception e1){
                    log.error("{}执行异常" ,interceptor ,e1);
                }
            }
        }
    }

}
